<template>
	<web-view v-if="url" :src="url"></web-view>
	<view v-else>
		<!-- #ifdef H5 -->
		<fui-sticky>
			<fui-nav-bar title="上传轮播" @leftClick="leftClick">
				<fui-icon name="arrowleft"></fui-icon>
			</fui-nav-bar>
		</fui-sticky>
		<!-- #endif -->

		<view class="upswiper">
			<LandScape></LandScape>
			<view style="padding: 32rpx;background-color: #fff;">
				<fui-section style="padding: 0;" title="轮播图类型" color="#fd5531" isLine></fui-section>
				<fui-radio-group name="radio" v-model="radioType" @change="changeType">
					<view class="fui-list__item">
						<fui-label>
							<view class="fui-align__center">
								<fui-radio value="0" checked></fui-radio>
								<text class="fui-text">首页</text>
							</view>
						</fui-label>
						<fui-label :margin="['0','0','0','40rpx']">
							<view class="fui-align__center">
								<fui-radio value="1"></fui-radio>
								<text class="fui-text">软件页</text>
							</view>
						</fui-label>
					</view>
				</fui-radio-group>
				<fui-section style="padding: 0;" title="上传轮播图(建议图片大小为350×180像素)" color="#fd5531" isLine></fui-section>
				<uni-file-picker :auto-upload="false" ref="files" style="margin-top: 20rpx;background-color: #f8f9f9;"
					@select="selectSwiper" @delete="deleteSwiper" file-mediatype="image" mode="grid" :limit="1"
					:imageStyles="imageStyles" />
				<fui-section style="padding: 0;margin-top: 20rpx;" title="轮播底部标题" color="#fd5531" isLine></fui-section>
				<fui-textarea :maxlength="20" radius='15' v-model="swiperTitle" style="margin-top: 20rpx;"
					backgroundColor="#f3f5f7" height="40rpx" min-height="40rpx" placeholder="请输入轮播底部标题"></fui-textarea>
				<fui-section style="padding: 0;margin-top: 20rpx;" title="轮播图天数" color="#fd5531" isLine></fui-section>

				<fui-input style="margin-top: 20rpx;" type="number" backgroundColor="#f3f5f7" v-model="swiperNum"
					borderTop placeholder="请输入轮播天数"></fui-input>

				<fui-section style="padding: 0;margin-top: 20rpx;" title="跳转链接" color="#fd5531" isLine></fui-section>
				<fui-radio-group name="radio" v-model="radioLink" @change="radiochange">
					<view class="fui-list__item">
						<fui-label>
							<view class="fui-align__center">
								<fui-radio value="0" checked></fui-radio>
								<text class="fui-text">内部文章</text>
							</view>
						</fui-label>
						<fui-label :margin="['0','0','0','40rpx']">
							<view class="fui-align__center">
								<fui-radio value="1"></fui-radio>
								<text class="fui-text">外部链接</text>
							</view>
						</fui-label>
					</view>
				</fui-radio-group>
				<fui-input v-if="radioLink==1" label="外部链接" v-model="outLink" borderTop
					placeholder="请输入相关链接"></fui-input>
			</view>
			<view v-if="radioLink==0" class="card_box">
				<fui-tabs :tabs="tabs" :current="currentTab" @change="changeTab"></fui-tabs>
				<mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback">
					<view style="padding: 20rpx;">
						<view class="card" v-for="(item,index) in goods" :class="listCurrent==index?'active':''">
							<fui-row style="height: 150rpx;" @click="setlist(index,item._id)">
								<fui-col :span="7">
									<view class="fui-col__item fui-color__black">
										<fui-lazyload width="180" height="148" :radius="20"
											:src="item[classifyImg[publish_type]].length>1&&Array.isArray(item[classifyImg[publish_type]])?item[classifyImg[publish_type]][0]:item[classifyImg[publish_type]]"></fui-lazyload>
										<view class="guanfang" v-if="item?.is_essence">
											官方推荐
										</view>
									</view>
								</fui-col>
								<view class="sort_item" v-if="item?.category_name">
									{{item?.category_name}}
								</view>
								<fui-col :span="17">
									<view style="height: 70rpx;width: 75%;" class="fui-col__item fui-col_text">
										<text class="fui-col_text-a">
											{{item.title}}
										</text>
									</view>
									<view class="sort" :class="!item.is_sticky&&!item.is_auto_refresh?'sort1':''">
										<view class="tap">
											<view class="zd" v-if="item.is_sticky">
												<text>置顶</text>
											</view>

											<view class="zdsx" v-if="item.is_auto_refresh">
												自动刷新
											</view>
										</view>
										<view class="browse">
											<text>浏览{{item.view_count}}次</text>
										</view>
									</view>
									<view class="fui-col_bottom">
										<view style="color: var(--fui-color-label);">
											<text>{{getDateDiff(item.refreshed_time)}}</text>
										</view>
									</view>
								</fui-col>
							</fui-row>
						</view>
					</view>
				</mescroll-body>
			</view>
		</view>
		<view v-if="btnShow"
			style="position: fixed;bottom: 30rpx;width: 100vw;z-index: 1;display: flex;justify-content: center;">
			<fui-button background="#fd5531" width="95%" text="确认上传轮播图" @click="upload"></fui-button>
		</view>
		<pay ref="uniPay"></pay>
	</view>
</template>

<script setup>
	const payApi = uniCloud.importObject('qc-pay', {
		customUI: true
	})
	import { setDiscount, getDateDiff } from "@/utils/index.js"
	import { LoginStore } from "@/store/modules/login.js";
	const api = uniCloud.importObject('qc-article', {
		customUI: true // 取消自动展示的交互提示界面
	})
	const getPricingApi = uniCloud.importObject('qc-asset', {
		customUI: true // 取消自动展示的交互提示界面
	})
	const marketingApi = uniCloud.importObject('qc-marketing', {
		customUI: true // 取消自动展示的交互提示界面
	})
	import useMescroll from "@/uni_modules/mescroll-uni/hooks/useMescroll.js";
	import { useUploadFile } from '@/hooks/useUploadFile.js'
	import { ref, reactive, computed, nextTick } from 'vue'
	const userInfo = computed(() => (LoginStore().userInfo))
	const { uploadFile, deleteFile, getFileInfo } = useUploadFile()
	import { onLoad, onPageScroll, onReachBottom, onReady } from "@dcloudio/uni-app";
	const classifyImg = ['articles_img', 'application_logo', 'connection_img', '', 'project_img', 'resource_img',
		'resources_img', 'exposure_img'
	]

	//图片大小
	const imageStyles = {
		width: 392,
		height: 190
	}
	//总价
	const price = ref(1)
	//单价
	const onePrice = ref(0)
	const banner_mix_time = ref(0) //最少天数
	let swiperNum = ref('')

	//是否可以上传
	const btnShow = ref(true)
	onLoad(async (e) => {
		if (e.title) {
			let item = JSON.parse(e.title)
			console.log(item);
			const res = await getPricingApi.getPricing({ category_id: item._id })
			console.log(res);
			onePrice.value = res?.data?.banner_cost
			banner_mix_time.value = res?.data?.banner_mix_time
		}
		// isUpload()
	})
	const isUpload = async () => {
		try {
			btnShow.value = true
		} catch (e) {
			btnShow.value = false
		}
	}
	let radioLink = ref(0)
	let listCurrent = ref(null)
	const goods = ref([])

	let tabs = ['文章', '应用']
	const currentTab = ref(0)

	const publish_type = ref("0")
	const changeTab = (e) => {
		listCurrent.value = null
		currentTab.value = e.index
		goods.value = []
		switch (e.index) {
			case 0:
				publish_type.value = String(e.index)
				break;
			case 1:
				publish_type.value = String(e.index)
				break;
		}
		getMescroll().resetUpScroll()
	}
	// 分页
	const {
		mescrollInit,
		downCallback,
		getMescroll
	} = useMescroll(onPageScroll, onReachBottom)
	const upCallback = async (mescroll) => {
		try {
			let params = {
				pageNum: mescroll.num,
				pageSize: mescroll.size,
				user_id: userInfo?.value?._id,
				publish_type: publish_type.value,
				release_status: 1
			}
			const res = await api.getUserAd(params)
			const curPageData = res.data || [] // 当前页数据
			if (mescroll.num == 1) goods.value = []; // 第一页需手动制空列表
			goods.value = goods.value.concat(curPageData); //追加新数据
			//方法一(推荐): 后台接口有返回列表的总页数 totalPage
			mescroll.endBySize(curPageData.length, res.total); //必传参数(当前页的数据个数, 总页数)
		} catch (e) {
			mescroll.endErr(); // 请求失败, 结束加载
		}
	}
	onReady(() => {
		nextTick(() => {
			getMescroll().resetUpScroll()
		})
	})

	//轮播类型
	const radioType = ref('0')
	const changeType = (e) => {
		console.log(e);
		radioType.value = e.detail.value
		isUpload()
	}
	const setlist = (e, id) => {
		outLink.value = id
		listCurrent.value = e
	}
	const radiochange = (e) => {
		outLink.value = null
		radioLink.value = e.detail.value
	}

	// #ifdef H5
	const leftClick = () => {
		uni.navigateBack()
	}
	// #endif

	//外部链接
	const outLink = ref(null)
	//轮播title
	const swiperTitle = ref(null)
	//轮播图片上传
	let fileIDs = []
	const selectSwiper = async (e) => {
		const res = await uploadFile(e.tempFiles, 'banner', 'file')
		fileIDs = res
	}
	const deleteSwiper = (e) => {
		deleteFile(fileIDs, e)
		fileIDs.forEach((vm, i) => {
			if (vm.filePath == e.tempFilePath) {
				fileIDs.splice(i, 1)
			}
		})
	}
	const url = ref()
	const uniPay = ref()
	const createPayment = (params) => {
		console.log(params);
		uniPay.value.open({
			data: {
				// alipayAppPayToH5Pay: true,
				// provider: "alipay",
				total_price: price.value,
				total_fee: setDiscount(userInfo?.value?.vipPower?.discount, price.value),
				subject: "发布轮播图",
				body: "发布轮播图",
				type: "recharge",
			},
			onCreate: res => {

			},
			onSuccess: async (res) => {
				if (res.code == 0 && res.user_order_success) {
					if (res.orderPaid == false && res.url) {
						const resApi = await payApi.addOrdersLog({
							...params,
							out_trade_no: res.out_trade_no,
							key: "发布轮播图"
						})
						if (resApi.id) {
							// #ifdef H5
							uni.navigateTo({
								url: `/pages/webView/webView?u=${encodeURIComponent(JSON.stringify(res.url))}`
							})
							// #endif
							// #ifdef APP-PLUS
							url.value = res.url
							// #endif
						}
					} else {
						const res1 = await api.createAd({
							...params,
							auth_audit: userInfo?.value?.vipPower
								?.auth_audit
						})
						uni.fui.toast(res1.errMsg)
						if (res1.errCode == 0) {
							setTimeout(() => {
								uni.navigateBack()
								uni.$emit("resetUpScroll")
							}, 1000)
						}
					}

					// uni.$emit("resetUpSwiper",true)
				}
			},
			onFail: res => {
				// 处理支付失败的逻辑

			},
			onCancel: res => {
				// 处理用户取消支付的逻辑

			}
		})
	}
	//内部跳转url
	const urlList = ["/pages/push/wzDetail/wzDetail", "/pages/tabbar/application/appDetail",
		"/pages/push/preheat/preheatDetail", "/pages/push/firstOrder/firstOrderDetail", "/pages/push/group/groupDetail"
	]
	//上传接口
	const upload = async () => {
		if (fileIDs.length == 0) return uni.fui.toast('请上传轮播图片')
		if (!swiperNum.value) return uni.fui.toast('请输入轮播天数')
		const pattern = /^[1-9]\d*$/;
		if (!pattern.test(swiperNum.value)) {
			swiperNum.value = ""
			return uni.fui.toast('轮播天数必须为整数')
		}
		if (swiperNum.value < banner_mix_time.value) return uni.fui.toast(`轮播最小天数为${banner_mix_time.value}`)
		//radioLink为true 内部文章 else 外部链接
		price.value = onePrice.value * swiperNum.value
		let params = {}
		if (radioLink.value == 0) {
			if (!outLink.value) return uni.fui.toast('请选择内部文章')
			params = {
				user_id: userInfo?.value?._id,
				publish_type: "3",
				bannerfile: fileIDs[0].fileID,
				category_id: radioType.value,
				title: swiperTitle.value,
				valid_time: swiperNum.value,
				open_url: `${urlList[currentTab.value]}?id=${outLink.value}`,
			}
			createPayment(params)

		} else {
			if (!outLink.value) return uni.fui.toast('请上传外部链接')
			if (outLink.value.indexOf('http') == -1) return uni.fui.toast('请输入正确的链接')
			params = {
				user_id: userInfo?.value?._id,
				publish_type: "3",
				bannerfile: fileIDs[0].fileID,
				category_id: radioType.value,
				title: swiperTitle.value,
				valid_time: swiperNum.value,
				open_url: outLink.value,
			}
			createPayment(params)
		}
	}
</script>

<style lang="scss" scoped>
	.card_box {
		padding-bottom: 100rpx;
	}

	.zdsx {
		margin-left: 20rpx;
		padding: 5rpx 15rpx;
		border-radius: 8rpx;
		color: #fff;
		background-color: var(--fui-color-primary);
	}

	.sort_item {
		position: absolute;
		right: -22rpx;
		top: -22rpx;
		background-color: #e6f3fe;
		color: #5babf2;
		border-top-right-radius: 16rpx;
		border-bottom-left-radius: 16rpx;
		padding: 8rpx 20rpx;
	}

	.sort1 {
		margin-top: 5rpx;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.fui-scroll__view {
		width: 520rpx;
		flex: 1;
		overflow: hidden;
	}

	.fui-ani__box {
		width: 640rpx;
		background: #FFFFFF;
		border-radius: 24rpx;
		padding-bottom: 64rpx;
	}

	.fui-hd__img {
		width: 100%;
		height: 192rpx;
		display: block;
	}

	.fui-ani__title {
		font-size: 36rpx;
		font-weight: 600;
		padding: 54rpx 0 32rpx;
		text-align: center;
	}

	.fui-desc {
		padding: 0 54rpx 82rpx;
		font-size: 24rpx;
		line-height: 48rpx;
		font-weight: 400;
		color: #333333;
		box-sizing: border-box;
	}

	.fui-desc text {
		color: #fd5531;
	}

	.fui-banner__item {
		width: 100%;
		height: 360rpx;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 34rpx;
		font-weight: 600;
		border-radius: 16rpx;
	}

	.fui-banner__wrap {
		border-radius: 16rpx;
		height: 360rpx;
	}

	.zdsx {
		padding: 5rpx 15rpx;
		border-radius: 8rpx;
		color: #fff;
		background-color: var(--fui-color-primary);
	}

	.zd {
		margin-right: 20rpx;
		color: #fff;
		padding: 3rpx 15rpx;
		border-radius: 8rpx;
		background-color: var(--fui-color-danger);
	}

	.box {
		padding: 32rpx;
	}

	.fui-col_img {
		position: relative;
	}

	.guanfang {
		font-size: 22rpx;
		color: #fff;
		padding: 5rpx 10rpx;
		background-color: #fc5531;
		position: absolute;
		top: 0px;
		border-radius: 5rpx;
	}

	.tap {
		font-size: 26rpx;
		display: flex;
	}

	.fui-col_bottom {
		display: flex;
		justify-content: flex-end;
		font-size: 22rpx;
		margin-top: 5rpx;
	}

	.tap_item {
		margin-right: 10rpx;
	}

	.sort {
		margin-top: 5rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.browse {
		color: var(--fui-color-label);
		font-size: 22rpx;
	}

	.card {
		position: relative;
		padding: 22rpx;
		background-color: var(--fui-bg-color);
		border-radius: 16rpx;
		margin-top: 12rpx;
	}

	.fui-col_text-a {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}


	.fui-col_text {
		font-size: 26rpx;
		font-weight: bold;
	}


	.index {
		display: flex;
		align-items: center;
		margin-bottom: 25rpx;
	}



	.active {
		border: 2px solid #fd5531;
	}



	.icon {
		display: inline-block;
		vertical-align: middle;
		padding-right: 5px;
		padding-bottom: 5rpx;
	}

	.fui-col_text-a {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.first {
		z-index: -1 !important;
		padding: 10rpx;
		border-radius: 16rpx;
		height: 135rpx;
		background: linear-gradient(to right top, #ff6f49, #ff5a5e);
		;
	}

	.fui-col_text {
		font-size: 26rpx;
		font-weight: bold;
	}

	.first-bottom {
		width: 94%;
		color: #d8d8d8;
		margin: 10rpx auto;
		display: flex;
		font-size: 24rpx;
		justify-content: space-between;
	}

	.first-title {
		display: flex;
	}

	.first-content {
		margin-left: 22rpx;
		color: #fff;
	}

	.first-text {
		margin-left: 5rpx;
		color: #fff;
		font-weight: bold;
	}

	.margintop {
		margin-top: 32rpx;
	}

	.index-box {
		background-color: var(--fui-bg-color-grey);
		padding: 32rpx
	}

	.swiper {
		height: 370rpx;
		border-radius: 16rpx;
	}

	.swiper-item {
		height: 100%;
		background-color: var(--fui-color-primary);
		border-radius: 20rpx;
	}

	.grid {
		border-radius: 16rpx;
		background-color: var(--fui-bg-color);
		margin-top: 32rpx;
		padding: 32rpx 0 32rpx 0;

		image {
			width: 100rpx;
			height: 100rpx;
		}
	}

	.fui-grid__cell {
		margin: auto;
		text-align: center;
	}

	.fui-text {
		margin-left: 10rpx;
	}

	.fui-list__item {
		display: flex;
		padding: 32rpx;
	}

	.upswiper {
		min-height: 100vh;
	}

	.fui-cover {
		width: 100%;
		height: 385rpx;
		display: block;
	}

	.fui-list__title {
		position: absolute;
		left: 0;
		bottom: 0;
		color: #fff;
		font-weight: 500;
		padding: 24rpx 20rpx;
		box-sizing: border-box;
		background: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.6));
	}
</style>